package tree.迭代bfs;

import po.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName N二叉树的锯齿形层序遍历103.java
 * @Description TODO
 * @createTime 2021年03月26日 13:01:00
 */
public class N二叉树的锯齿形层序遍历103 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) {
            return lists;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        //todo 计算次数，偶数次为逆序，奇数次为顺序
        int circle = 0;
        while (!deque.isEmpty()) {
            Deque<Integer> list = new LinkedList<>();
            int size = deque.size();
            for (int i = 0; i < size; i++) {
                //todo 这里用队列存储，方便前插和后插
                TreeNode node = deque.poll();
                if (circle % 2 == 0){
                    list.offerLast(node.val);
                }else {
                    list.offerFirst(node.val);
                }
                if (node.left != null) {
                    deque.offer(node.left);
                }
                if (node.right != null) {
                    deque.offer(node.right);
                }
            }
            circle = circle + 1;
            lists.add(new LinkedList<>(list));
        }
        return lists;
    }
}
